
package com.oahcfly.chgame.core.helper;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;

import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.PropertiesUtils;
import com.oahcfly.chgame.core.mvc.CHGame;
import com.oahcfly.chgame.util.CHLog;

public class CHFileHelper {

	protected static void loadAssetsByDesktop () {
		if (Gdx.app.getType() != ApplicationType.Desktop) {
			FileHandle[] handles = getFileHandles("game");
			Array<File> fileArray = new Array<File>();
			for (FileHandle fileHandle : handles) {
				fileArray.add(fileHandle.file());
			}
			return;
		}
		try {
			File directory = new File("");// 参数为空
			String courseFile = directory.getCanonicalPath();
			courseFile = courseFile.replace("desktop", "android");
			File assetFile = new File(courseFile + File.separator + "assets/game");
			// System.out.println("parent:" + courseFile);

			File[] files = assetFile.listFiles();
			Array<File> fileArray = new Array<File>();
			for (File file : files) {
				fileArray.add(file);
			}

		} catch (IOException ioException) {
			Gdx.app.error("CHFileHandler", "load assets error :" + ioException.getLocalizedMessage());
		}
	}

	/** <pre>
	 * 读取文件下所有文件
	 * 
	 * date: 2015-1-14
	 * </pre>
	 * 
	 * @author caohao
	 * @param fileName
	 * @return */
	public static FileHandle[] getFileHandles (String fileName) {
		if (Gdx.app.getType() == ApplicationType.Desktop) {

			try {
				File directory = new File("");// 参数为空
				String courseFile = directory.getCanonicalPath();
				courseFile = courseFile.replace("desktop", "android");
				File assetFile = new File(courseFile + File.separator + "assets/" + fileName);
				// System.out.println("parent:" + courseFile);

				File[] files = assetFile.listFiles();
				if (files == null) return new FileHandle[] {};
				FileHandle[] handles = new FileHandle[files.length];
				for (int i = 0, l = files.length; i < l; i++) {
					handles[i] = new FileHandle(files[i]);
				}

				return handles;
			} catch (IOException ioException) {
				Gdx.app.error("CHFileHandler", "load assets error :" + ioException.getLocalizedMessage());
			}
		}

		FileHandle parentFileHandle = Gdx.files.internal(fileName);
		return parentFileHandle.list();
	}

	/** <pre>
	 * 根据文件名，获取FileHandle
	 * [效率不怎么高]
	 * date: 2015-1-14
	 * </pre>
	 * 
	 * @author caohao
	 * @param pngName
	 * @return */
	public static FileHandle searchFileHandle (String dirName, String pngName) {
		FileHandle parentFileHandle = Gdx.files.internal(dirName);
		FileHandle[] listFileHandles = parentFileHandle.list();
		for (FileHandle tmpFileHandle : listFileHandles) {
			if (tmpFileHandle.isDirectory()) {
				// 是文件目录
				FileHandle fileHandle = searchFileHandle(tmpFileHandle.name(), pngName);
				if (fileHandle != null) return fileHandle;
			} else if (tmpFileHandle.name().equals(pngName)) {
				return tmpFileHandle;
			}
		}
		return null;
	}

	public static void autoWriteExmlUI () {
		// 读取exml目录，在ui下创建对应类

		for (Map.Entry<String, String> entry : resMap.entrySet()) {
			if(entry.getKey().contains("exml")){
				
			}
		}
	}

	private static HashMap<String, String> resMap = new HashMap<String, String>();

	/** 自动读写资源路径 */
	public static void autoWriteResInfo () {
		loadRes("");

		// 读取模板
		FileHandle resFileHandle = Gdx.files.classpath("com/oahcfly/chgame/core/CHResTemplate.a");
		BufferedReader bufferedReader = new BufferedReader(resFileHandle.reader());
		String line = null;
		StringBuffer contentBuffer = new StringBuffer();
		try {
			while ((line = bufferedReader.readLine()) != null) {
				if (line.contains("$")) {
					// 替换变量
					String demo = line.replace("$", "");
					for (Map.Entry<String, String> entry : resMap.entrySet()) {
						String a = String.format(demo, entry.getKey(), entry.getValue()) + "\n";
						contentBuffer.append(a);
					}
				} else if (line.contains("#")) {
					// 替换包名
					line = String.format(line.replace("#", ""), getGameClassPath());
					line = line.replaceAll("/", ".");
					contentBuffer.append(line + "\n");
				} else {
					contentBuffer.append(line + "\n");
				}
			}
		} catch (IOException e) {
			CHLog.log(e.getLocalizedMessage());
			try {
				bufferedReader.close();
			} catch (IOException e1) {
				bufferedReader = null;
			}
		}

		if (contentBuffer.length() > 0) {
			// 工程名称
			String projectname = System.getProperty("user.dir").replace("desktop", "core");
			// =/Users/haocao/git/CHGame/my-gdx-game-core
			projectname = projectname.substring(projectname.lastIndexOf("/") + 1);
			// 在相应包目录下创建类文件
			String coreProjectSrc = String.format("../%s/src/", projectname);
			String resJavaFile = coreProjectSrc + getGameClassPath();
			File resFile = new File(resJavaFile);
			if (!resFile.exists()) {
				resFile.mkdir();
			}
			FileHandle fileHandle = new FileHandle(resFile + "/CHRes.java");
			fileHandle.writeBytes(contentBuffer.toString().getBytes(), false);
		}
	}

	/** 获取CHGame的继续类所在包路径
	 * @return */
	private static String getGameClassPath () {
		Class<?> gameclass = CHGame.getInstance().getClass();
		String gameClassPath = gameclass.getName().replaceAll("\\.", "/");
		gameClassPath = gameClassPath.substring(0, gameClassPath.lastIndexOf("/"));
		return gameClassPath;
	}

	/** 读取assets目录下全部资源
	 * 
	 * @param path */
	private static void loadRes (String path) {
		// System.err.println(path);
		// 处理path
		int idxAssetEnd = path.contains("assets") ? path.lastIndexOf("assets") + 7 : -1;
		if (idxAssetEnd > 6) {
			///Users/haocao/git/CHGameFrame/android/assets/exml 获取目录
			path = path.substring(idxAssetEnd);
		}
		FileHandle[] fileHandles = CHFileHelper.getFileHandles(path);
		for (FileHandle fileHandle : fileHandles) {
			if (fileHandle.isDirectory()) {
				// 是目录，继续遍历
				loadRes(fileHandle.path());
			} else {
				// 是文件
				String key = fileHandle.name().replaceAll("\\.", "_");
				if (key.contains("DS_Store")) {
					continue;
				}
				if (Character.isDigit(key.toCharArray()[0])) {
					// 数字打头的文件，需要处理下
					key = "_" + key;
				}
				String value = fileHandle.path();
				int assetEnd = value.lastIndexOf("assets");
				resMap.put(key, value.substring(assetEnd + 7));
			}
		}
	}

	/** 加载.properties文件
	 * @param path
	 * @return */
	public static ObjectMap<String, String> loadPropertyFile (String path) {
		Reader reader = Gdx.files.internal(path).reader();
		ObjectMap<String, String> properties = new ObjectMap<String, String>();
		try {
			PropertiesUtils.load(properties, reader);
		} catch (IOException e) {
			CHLog.error(e.getLocalizedMessage());
		}
		return properties;
	}
}
